package com.fraud.controller;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

import org.primefaces.event.RowEditEvent;

import com.fraud.dao.BolgeDao;
import com.fraud.dao.SubeDao;
import com.fraud.model.entity.Bolge;
import com.fraud.model.entity.Sube;
import com.fraud.model.type.BaglantiTipi;

@ManagedBean(name = "subeController")
public class SubeController implements Serializable {

	private Sube sube;

	private List<Sube> allSubes;

	@EJB
	SubeDao subeDao;

	@EJB
	BolgeDao bolgeDao;
	
	private int bolgeId;
	
	
	
	
	
	public int getBolgeId() {
		return bolgeId;
	}

	public void setBolgeId(int bolgeId) {
		this.bolgeId = bolgeId;
	}

	public Sube getSube() {
		return sube;
	}

	public void setSube(Sube sube) {
		this.sube = sube;
	}

	public List<Sube> getAllSubes() {
		return allSubes;
	}

	public void setAllSubes(List<Sube> allSubes) {
		this.allSubes = allSubes;
	}


	@PostConstruct
	public void init() {
		try {
			sube = new Sube();
			allSubes = subeDao.getAllSubes();
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	public BaglantiTipi[] getBaglantiList() {
		return BaglantiTipi.values();

	}

	
	public List<Bolge> getBolgeList() {
		
		return  bolgeDao.getAll();
		
//		List<Bolge> items = new ArrayList<Bolge>(list.size());
//		for(Bolge value : list){
//			items.add(value);
//		}
//		return items;

	}


	public String goToPage() {
		return "both/" + "subeIslem" + "?faces-redirect=true";
	}


	public void createSube() {

		FacesContext context = FacesContext.getCurrentInstance();
		try {

			sube.setBolge(bolgeDao.getBolge(getBolgeId()));
			
			subeDao.insert(sube);

			context.addMessage(null, new FacesMessage("Uyarı",
					"İşleminiz başarı ile tamamlandı."));

			sube = new Sube();
			init();

		} catch (Exception e) {
			context.addMessage(null, new FacesMessage("Hata",
					"İşleminiz Yapılamadı."));
			return;
		}

	}

	

	public void onRowCancel(RowEditEvent event) {
		Sube sub = ((Sube) event.getObject());

		boolean result = subeDao.delete(sub);
		String message = "";
		if (result) {
			message = "Başarılı";
		} else {
			message = "Başarırız";
		}

		FacesMessage msg = new FacesMessage("Sube Silindi", message);
		FacesContext.getCurrentInstance().addMessage(null, msg);

		init();
	}

	public void onRowEdit(RowEditEvent event) {

		Sube sub = ((Sube) event.getObject());

		subeDao.merge(sub);

		FacesMessage msg = new FacesMessage("Sube Bilgileri Güncellendi",
				"Başarılı");
		FacesContext.getCurrentInstance().addMessage(null, msg);
		init();
	}

	

}